package com.yylending.las.personal.loan;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import butterknife.ButterKnife;
import com.yyfax.common.recyclerview.adapter.CommonAdapter;
import com.yyfax.common.recyclerview.adapter.MultiItemTypeAdapter;
import com.yyfax.common.recyclerview.base.ViewHolder;
import com.yyfax.common.recyclerview.listener.OnRefreshListener;
import com.yyfax.common.recyclerview.view.IRecyclerView;
import com.yyfax.common.recyclerview.wrapper.StatesAdapter;
import com.yyfax.common.recyclerview.wrapper.WrapperAdapter;
import com.yyfax.common.tools.DensityUtil;
import com.yyfax.common.tools.IMMLeaks;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.R;
import com.yylending.las.StatIDSet;
import com.yylending.las.YJKD;
import com.yylending.las.base.BaseActivity;
import com.yylending.las.common.utils.FormatUtils;
import com.yylending.las.common.utils.TimeUtils;
import com.yylending.las.common.widgets.Divider;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 我的借款列表
 * Created by ying_he on 2017/6/5.<br>
 * Copyright  2017 www.yylending.com. All Rights Reserved.<br><br>
 */
public class LoanListActivity extends BaseActivity implements LoanListPresenter.View,
		StatesAdapter.RetryClickListener, OnRefreshListener, MultiItemTypeAdapter.OnItemClickListener {

	private static final String TAG = LoanListActivity.class.getSimpleName();
	private static final int LOADER_ID = 1;

	public static final String LOAN_STATUS_CODE_IN_REVIEW = "0"; // 审核中
	public static final String LOAN_STATUS_CODE_IN_REPAY = "1"; // 还款中
	public static final String LOAN_STATUS_CODE_PAY_OFF = "2"; // 已还清
	public static final String LOAN_STATUS_CODE_NEGATIVE = "3"; // 已否决
	public static final String LOAN_STATUS_CODE_EXPIRED = "4"; // 已失效

	private static final String FLAG_HAS_OVERDUE = "1"; // 已逾期

	private LoanListPresenter mPresenter;

	public IRecyclerView mRecyclerView;
	public WrapperAdapter mWrapAdapter;
	private MultiItemTypeAdapter<LoanListModel.Loan.LoanDetail> mAdapter;
	private List<LoanListModel.Loan.LoanDetail> mLoanList = new ArrayList<>();
	private Divider mDivider;

	public static void start(Activity aty) {
		Intent intent = new Intent(aty, LoanListActivity.class);
		aty.startActivity(intent);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		IMMLeaks.fixFocusedViewLeak(YJKD.app());
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_loan_list);
		EventAgent.register(this);
		ButterKnife.bind(this);
		initData();
		getSupportLoaderManager().initLoader(LOADER_ID, null, this);
	}

	private void initData() {
		setTitle(R.string.my_loan);

		mRecyclerView = (IRecyclerView) findViewById(R.id.loan_list_rv);
		mRecyclerView.setLayoutManager(new GridLayoutManager(this, 1));

		mAdapter = new CommonAdapter<LoanListModel.Loan.LoanDetail>(R.layout.adapter_item_loan_list, mLoanList, mRecyclerView.getItemViewDelegateManager()) {
			@Override
			protected void convert(ViewHolder holder, LoanListModel.Loan.LoanDetail loan, int position) {
				holder.setText(R.id.loan_date_tv, TimeUtils.formatDateTimeSlash(Long.valueOf(loan.applyDate))); // 借款日期
				holder.setText(R.id.loan_sum_tv, FormatUtils.getDecoratedAmountWithSymbol(loan.loanAmount)); // 借款金额

				String strStatus = "";
				switch (loan.loanStatus) {
					case LOAN_STATUS_CODE_IN_REVIEW:
						strStatus = getString(R.string.loan_status_in_review);
						break;
					case LOAN_STATUS_CODE_IN_REPAY:
						strStatus = getString(R.string.loan_status_in_repay);
						break;
					case LOAN_STATUS_CODE_PAY_OFF:
						strStatus = getString(R.string.loan_status_pay_off);
						break;
					case LOAN_STATUS_CODE_NEGATIVE:
						strStatus = getString(R.string.loan_status_negative);
						break;
					case LOAN_STATUS_CODE_EXPIRED:
						strStatus = getString(R.string.loan_status_expired);
						break;
					default:
						break;
				}
				holder.setText(R.id.loan_status_tv, strStatus); // 申请状态
				if (TextUtils.equals(FLAG_HAS_OVERDUE, loan.isOverDue)) {
					holder.getView(R.id.flag_overdue_iv).setVisibility(View.VISIBLE);
				} else {
					holder.getView(R.id.flag_overdue_iv).setVisibility(View.GONE);
				}

				// TODO: 2017/7/18 这里看下有没有更优雅的方式.
				if (loan.isClickable()) {
					((TextView) holder.getView(R.id.label_loan_date_tv)).setTextColor(getResources().getColor(R.color.color_999999));
					((TextView) holder.getView(R.id.label_loan_sum_tv)).setTextColor(getResources().getColor(R.color.color_999999));
					((TextView) holder.getView(R.id.label_loan_status_tv)).setTextColor(getResources().getColor(R.color.color_999999));

					((TextView) holder.getView(R.id.loan_date_tv)).setTextColor(getResources().getColor(R.color.color_333333));
					((TextView) holder.getView(R.id.loan_sum_tv)).setTextColor(getResources().getColor(R.color.color_333333));
					((TextView) holder.getView(R.id.loan_status_tv)).setTextColor(getResources().getColor(R.color.color_333333));
				} else {
					((TextView) holder.getView(R.id.label_loan_date_tv)).setTextColor(getResources().getColor(R.color.color_cccccc));
					((TextView) holder.getView(R.id.label_loan_sum_tv)).setTextColor(getResources().getColor(R.color.color_cccccc));
					((TextView) holder.getView(R.id.label_loan_status_tv)).setTextColor(getResources().getColor(R.color.color_cccccc));

					((TextView) holder.getView(R.id.loan_date_tv)).setTextColor(getResources().getColor(R.color.color_cccccc));
					((TextView) holder.getView(R.id.loan_sum_tv)).setTextColor(getResources().getColor(R.color.color_cccccc));
					((TextView) holder.getView(R.id.loan_status_tv)).setTextColor(getResources().getColor(R.color.color_cccccc));
				}
			}
		};

		mWrapAdapter = new WrapperAdapter(mAdapter, mRecyclerView, this, R.layout.no_loan_data, R.layout.include_view_no_network);
		mDivider = new Divider(DensityUtil.dip2px(this, 10f), getResources().getColor(R.color.color_f1f3f7), false,
				0, 0, 0, DensityUtil.dip2px(this, 10f), 0);
		mRecyclerView.addItemDecoration(mDivider);
		mWrapAdapter.setOnItemClickListener(this);
		mWrapAdapter.setRetryClickListener(this);
		mRecyclerView.setAdapter(mWrapAdapter);
		mRecyclerView.setOnRefreshListener(this);
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return new PresenterLoader<>(this, new LoanListPresenter.Generator());
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		mPresenter = (LoanListPresenter) data;
		mPresenter.attach(this);
		mRecyclerView.setRefreshing(true);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		getSupportLoaderManager().destroyLoader(LOADER_ID);
		EventAgent.unregister(this);
	}

	private void requestData() {
		mPresenter.obtainLoanList();
	}

	@Override
	public void refreshSuccess(ArrayList<LoanListModel.Loan.LoanDetail> list) {
		mRecyclerView.stopRefreshing();
		mLoanList.clear();
		mLoanList.addAll(list);
		mWrapAdapter.refreshData(mLoanList);

		if (list.size() <= 0) {
			// 必须删除,否则会出现多余的空隙.
			mRecyclerView.removeItemDecoration(mDivider);
			mWrapAdapter.setState(StatesAdapter.STATE_EMPTY);
		}
	}

	@Override
	public void obtainLoanListFailed(String tips) {
		mRecyclerView.setRefreshing(false);
		mWrapAdapter.setState(StatesAdapter.STATE_ERROR);
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips, int functionalCode) {
		super.onFunctionalError(e, autoTips, functionalCode);
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mRecyclerView.stopRefreshing();
				mWrapAdapter.setState(StatesAdapter.STATE_ERROR);
			}
		});
	}

	@Override
	public void onItemClick(View view, ViewHolder holder, int position, int viewType) {
		int pos = holder.getAdapterPosition() - 1;
		LoanListModel.Loan.LoanDetail loanDetail = mLoanList.get(pos);
		HashMap<String, String> map = new HashMap<>();
		map.put(StatService.ATTRIBUTE_KEY_ONE, mLoanList.size() + "");
		map.put(StatService.ATTRIBUTE_KEY_TWO, loanDetail.loanStatus);
		StatService.onEvent(this, StatIDSet.EVENT_ID_VIEW_BORROWING_LIST, map);
		if (loanDetail.isClickable()) {
			LoanDetailActivity.start(this, loanDetail.loanNo, loanDetail.loanStatus);
		}
	}

	@Override
	public boolean onItemLongClick(View view, ViewHolder holder, int position, int viewType) {
		return true;
	}

	@Override
	public void onRefresh() {
		requestData();
	}

	@Override
	public void onRetry() {
		mRecyclerView.setRefreshing(true);
	}
}
